<template>
  <view class="plan-page">
    <!-- 胶囊导航（修改：移除背景色和阴影） -->
    <view class="folder-nav-container">
      <CapsuleNav 
        :items="folders" 
        :activeIndex="activeFolderIndex"
        :pendingCount="activeFolderPendingCount"
        showBadge
        allowEdit
        @change="switchFolder"
        @add-folder="showAddFolderDialog"
        @delete-folder="showDeleteFolderDialog"
        @rename-folder="handleRenameTrigger" 
      />
    </view>

    <!-- 计划列表 -->
    <scroll-view 
      class="plan-list"
      scroll-y
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="refreshData"
    >
      <view v-if="currentPlans.length === 0" class="empty-tip">
        <uni-icons type="info" size="24" color="#999"></uni-icons>
        <text>当前文件夹暂无计划</text>
      </view>

      <PlanCard
        v-for="plan in currentPlans"
        :key="plan.id"
        :plan="plan"
        :folderName="activeFolder"
        @edit="openEditor(plan.id)"
      />
    </scroll-view>

    <!-- 计划编辑器 -->
    <PlanEditor ref="editor" :folderName="activeFolder" @saved="refreshData" @deleted="refreshData" />

    <!-- 新建按钮 -->
    <view class="add-button" @click="openEditor(null)">
      <uni-icons type="plus" size="24" color="white"></uni-icons>
    </view>

    <!-- 添加文件夹弹窗 -->
    <uni-popup ref="addFolderPopup" type="dialog">
      <uni-popup-dialog
        mode="input"
        title="新建文件夹"
        placeholder="输入文件夹名称"
        @confirm="addFolder"
      ></uni-popup-dialog>
    </uni-popup>

    <!-- 重命名文件夹弹窗 -->
    <uni-popup ref="renameFolderPopup" type="dialog">
      <uni-popup-dialog
        mode="input"
        title="重命名文件夹"
        :value="renameFolderData.oldName"
        placeholder="输入新名称"
        @confirm="confirmRenameFolder"
      ></uni-popup-dialog>
    </uni-popup>

    <!-- 删除文件夹弹窗 -->
    <uni-popup ref="deleteFolderPopup" type="dialog">
      <uni-popup-dialog
        mode="base"
        title="删除文件夹"
        :content="`确定删除文件夹【${deleteFolderData.name}】吗？(包含${deleteFolderData.planCount}个计划)`"
        @confirm="confirmDeleteFolder"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { usePlanStore } from '@/stores/planStore'
import CapsuleNav from '@/components/common/CapsuleNav.vue'
import PlanCard from '@/components/modules/plan/PlanCard.vue'
import PlanEditor from '@/components/modules/plan/PlanEditor.vue'

const planStore = usePlanStore()
const editor = ref(null)
const addFolderPopup = ref(null)
const renameFolderPopup = ref(null)
const deleteFolderPopup = ref(null)
const activeFolderIndex = ref(0)
const isRefreshing = ref(false)

const deleteFolderData = ref({
  name: '',
  planCount: 0
})

const renameFolderData = ref({
  oldName: '',
  newName: ''
})

onMounted(async () => {
  await planStore.initFromStorage()
})

const folders = computed(() => planStore.folders)
const activeFolder = computed(() => planStore.activeFolder)
const currentPlans = computed(() => planStore.currentPlans)
const activeFolderPendingCount = computed(() => planStore.activeFolderPendingCount)

const switchFolder = (index) => {
  if (index >= 0 && index < folders.value.length) {
    planStore.switchFolder(folders.value[index])
    activeFolderIndex.value = index
  }
}

const refreshData = async () => {
  isRefreshing.value = true
  await planStore.initFromStorage()
  setTimeout(() => isRefreshing.value = false, 500)
}

const openEditor = (planId) => {
  editor.value?.open(planId)
}

const showAddFolderDialog = () => {
  addFolderPopup.value.open()
}

const addFolder = async (name) => {
  if (!name.trim()) {
    uni.showToast({ title: '名称不能为空', icon: 'none' })
    return
  }

  const success = await planStore.addFolder(name.trim())
  if (success) {
    uni.showToast({ title: '创建成功' })
    await refreshData()
    const index = folders.value.indexOf(name.trim())
    if (index !== -1) {
      switchFolder(index)
    }
  } else {
    uni.showToast({ title: '文件夹已存在', icon: 'none' })
  }
}

const handleRenameTrigger = ({ oldName }) => {
  renameFolderData.value = { oldName, newName: oldName }
  renameFolderPopup.value.open()
}

const confirmRenameFolder = async (newName) => {
  if (!newName || !newName.trim()) {
    uni.showToast({ title: '名称不能为空', icon: 'none' })
    return
  }

  if (newName.trim() === renameFolderData.value.oldName) {
    uni.showToast({ title: '名称未改变', icon: 'none' })
    return
  }

  try {
    const success = await planStore.renameFolder(
      renameFolderData.value.oldName, 
      newName.trim()
    )
    
    if (success) {
      uni.showToast({ title: '重命名成功' })
      await refreshData()
    } else {
      uni.showToast({ title: '文件夹已存在', icon: 'none' })
    }
  } catch (err) {
    console.error('重命名文件夹失败:', err)
    uni.showToast({ title: '重命名失败', icon: 'none' })
  }
}

const showDeleteFolderDialog = (folderName) => {
  if (folderName === '默认文件夹') {
    uni.showToast({ title: '不能删除默认文件夹', icon: 'none' })
    return
  }

  deleteFolderData.value = {
    name: folderName,
    planCount: planStore.plans[folderName]?.length || 0
  }
  deleteFolderPopup.value.open()
}

const confirmDeleteFolder = async () => {
  try {
    const success = await planStore.deleteFolder(deleteFolderData.value.name)
    if (success) {
      uni.showToast({ title: '删除成功' })
      await refreshData()
      switchFolder(0)
    } else {
      uni.showToast({ title: '删除失败', icon: 'none' })
    }
  } catch (err) {
    console.error('删除文件夹失败:', err)
    uni.showToast({ title: '删除失败', icon: 'none' })
  }
}
</script>

<style scoped>
.plan-page {
  height: 100vh;
  background-color: var(--background-color);
  display: flex;
  flex-direction: column;
}

/* 修改：移除背景色和阴影 */
.folder-nav-container {
  padding: 12px 16px;
  background-color: var(--background-color);
}

.plan-list {
  flex: 1;
  padding: 8px 0;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #999;
}

.empty-tip text {
  margin-top: 8px;
  font-size: 14px;
}

.add-button {
  position: fixed;
  right: 24px;
  bottom: 24px;
  width: 56px;
  height: 56px;
  background-color: var(--primary-color);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(135, 206, 235, 0.3);
  z-index: 100;
}
</style>